<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          :status-icon="true"
          class="demo-ruleForm"
        >
          <el-form-item
            v-if="user.level < 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              clearable
              placeholder="请选择迁移对象所属村"
              @change="change"
            />
          </el-form-item>
          
          <el-form-item
            label="所属组"
            prop="group"
          >
            <el-select
              v-model.number="ruleForm.group"
              placeholder="请选择所属组"
              clearable
            >
              <el-option
                v-for="item in groupAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- 村民信息 -->
          <el-form-item
            label="姓名"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入村民姓名"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="性别"
            prop="sex"
          >
            <el-select
              v-model.number="ruleForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option
                label="男"
                :value="0"
              />
              <el-option
                label="女"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="民族"
            prop="nation"
          >
            <el-select
              v-model.number="ruleForm.nation"
              placeholder="请选择所属民族"
              clearable
            >
              <el-option
                v-for="(item, index) in nationAtt"
                :key="index"
                :label="item"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="phone"
          >
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入村民手机号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="身份证号"
            prop="identityNumber"
          >
            <el-input
              v-model="ruleForm.identityNumber"
              placeholder="请输入村民身份证号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="家庭地址"
            prop="address"
          >
            <el-input
              v-model="ruleForm.address"
              placeholder="请输入村民家庭地址"
              clearable
            />
          </el-form-item>
          <!-- 村民信息 -->
          <el-form-item
            label="迁移类型"
            prop="type"
          >
            <el-select
              v-model.number="ruleForm.type"
              placeholder="请选择迁移状态"
              clearable
            >
              <el-option
                label="迁入"
                :value="1"
              />
              <el-option
                label="迁出"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="迁移时间"
            prop="migrationTime"
          >
            <el-date-picker
              v-model="ruleForm.migrationTime"
              align="right"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="迁移地点"
            prop="migrationLocation"
          >
            <el-input
              v-model="ruleForm.migrationLocation"
              type="textarea"
              :rows="2"
              clearable
            />
          </el-form-item>

          <relatedDocuments
            :related-documents="documents"
            @getRes="getResRelatedDocuments"
          />

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
import relatedDocuments from "@/components/My-Components/relatedDocuments";
export default {
  name: "Form",
  components: {
    relatedDocuments,
  },
  props: {
    id: {},
  },
  data() {
    return {
      ruleForm: {
        villageWrap: [],
        village: "",
        group: "",
        type: "",
        migrationTime: "",
        migrationLocation: "",
        image: [],
        file: [],
        
        name: "",
        //性别
        sex: 0,  
        //民族
        nation: 1,
        //手机号
        // phone: "",
        //身份证号
        identityNumber: "",
        //籍贯
        address: "",
      },
      rules: {
        migrationLocation: [
          { required: false, message: "请输入迁移地址", trigger: "blur" },
        ],
        villageWrap: [
          { required: true, message: "请选择迁移对象所属村", trigger: "change" },
        ],
        migrationTime: [
          { required: true, message: "请选择迁移时间", trigger: "change" },
        ],
        image: [
          { required: false, message: "请上传相关图片" },
        ],
        file: [
          { required: false, message: "请上传相关文件" },
        ],
        type: [
          {
            required: true,
            message: "请选择迁移类型",
            trigger: "change",
          },
        ],

        'name': [
          { required: true, message: "请输入村民姓名", trigger: "blur" }
        ],
        'sex': [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        'nation': [
          { required: true, message: "请选择所属民族", trigger: "change" }
        ],
        'phone': [
          {
                required: false, message: "请填写迁移村民的手机号", trigger: "blur"
          }
        ],
        'identityNumber': [
          {
                required: false, message: "请填写迁移村民的身份证号", trigger: "blur"
          }
        ],
        'address': [
          {
                required: false, message: "请填写迁移村民的家庭地址", trigger: "blur"
          }
        ],
      },

      nationAtt: [
        "汉族",
        "蒙古族",
        "回族",
        "藏族",
        "维吾尔族",
        "苗族",
        "彝族",
        "壮族",
        "布依族",
        "朝鲜族",
        "满族",
        "侗族",
        "瑶族",
        "白族",
        "土家族",
        "哈尼族",
        "哈萨克族",
        "傣族",
        "黎族",
        "傈僳族",
        "佤族",
        "畲族",
        "高山族",
        "拉祜族",
        "水族",
        "东乡族",
        "纳西族",
        "景颇族",
        "柯尔克孜族",
        "土族",
        "达斡尔族",
        "仫佬族",
        "羌族",
        "布朗族",
        "撒拉族",
        "毛南族",
        "仡佬族",
        "锡伯族",
        "阿昌族",
        "普米族",
        "塔吉克族",
        "怒族",
        "乌孜别克族",
        "俄罗斯族",
        "鄂温克族",
        "德昂族",
        "保安族",
        "裕固族",
        "京族",
        "塔塔尔族",
        "独龙族",
        "鄂伦春族",
        "赫哲族",
        "门巴族",
        "珞巴族",
        "基诺族",
      ],
      dialogImageUrl: "",
      dialogVisible: false,
      imgAtt: [],
      groupAtt: [],
      createForm: {},
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      relatedDocuments: [],
      documents: [],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  watch: {
  },
  async created() {
    this.init();
    this.id && this.fetchData(this.id);
  },
  
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //校验 手机号 与 身份证号 家庭地址 
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getResRelatedDocuments(val) {
      this.relatedDocuments = val
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
      this.createForm.relatedDocuments = this.relatedDocuments;
      this.clearNullField(this.createForm, 'group')
    },
    async create() {
      this.resPip();
      console.log(JSON.stringify(this.createForm));
      const res = await this.$http.post(`/migrate`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Migrate" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/migrate/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Migrate" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`migrate/${id}?join=village&join=group&join=village.town`);

      this.groupAtt = res.data.village.group
      
      this.relatedDocuments = res.data.relatedDocuments
      this.documents = res.data.relatedDocuments

      const town = await this.$http.get(`town/${res.data.village.town.id}?join=area`);

      res.data.villageWrap = [town.data.area.id, res.data.village.town.id, res.data.village.id];

      this.change(res.data.villageWrap)

      res.data.village = res.data.village.id
      res.data.group = res.data.group && res.data.group.id
      this.change(res.data.villageWrap)
      //处理关联
      this.ruleForm = Object.assign({}, res.data);
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.ruleForm.village = val[val.length - 1];
      this.ruleForm.group = ""
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=group`)
      this.groupAtt = res.data.group
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 3) {
        //村级
        this.change([this.user.village.id])
      } 
    },
  },
};
</script>
